﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using P2P.Main.Session;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using P2P.Network.ExtensionMethods;

namespace P2P.Main.Handler
{
    /// <summary>
    /// 客户端心跳处理Handler
    /// </summary>
    public class ClientHeartbeatHandler
    {
        private ApiProtocol apiProtocol;

        public ClientHeartbeatHandler(ApiProtocol apiProtocol) 
        {
           this.apiProtocol = apiProtocol;
        }

        /// <summary>
        /// 客户端心跳应答
        /// </summary>
        public void ClientHeartbeat() 
        {
            string AccountId = (string)apiProtocol.Params["AccountId"];

            string ip = apiProtocol.RemoteEndPoint.Address.ToString();
            int port = apiProtocol.RemoteEndPoint.Port;

            ActiveNodeSessionManager.Instance.Flush(AccountId, ip
                   , port);

            JObject data = new JObject();
            data.Add("Name", "Heartbeat");
            data.Add("Method", "MainHeartbeatAck");
            data.Add("Version", "1.0");

            JObject param = new JObject();
            param.Add("Msg", $"Client at IP: {ip},Port: {port},Name: {AccountId} is active.");
            data.Add("Params", param);
            string ack = JsonConvert.SerializeObject(R<JObject>.Ok(data));

            apiProtocol.Socket.SendTo(ack, apiProtocol.RemoteEndPoint);
        }
    }
}
